<template>
  <div>
    <div style="padding-bottom: 64px" v-if="!abnormalS">
      <infoCard ref="infoCard" />
      <div class="xq-form-wrapper p24 mt24">
        <div style="display: flex; width: 100%; margin-bottom: 16px; justify-content: space-between">
          <titborder> 上传数据预览 </titborder>
          <div>
            <a-button class="mr12" :disabled="!selectedRowKeys.length" @click="onEditMoney()"> 批量编辑薪资 </a-button>
            <QrcodeForPay title="微信扫码录入" :showFunc="showQrcode" />
            <a-button class="mr12" @click="onSelect"> 新增计薪人员 </a-button>
            <a-upload ref="upload" :showUploadList="false" :file-list="fileList" :before-upload="beforeUpload">
              <a-button type="primary" style="margin-top: 10px"> 上传发薪表 </a-button>
            </a-upload>
          </div>
        </div>
        <a-spin :spinning="spinning" class="xq-form-content">
          <XqTable
            :customize="FormJson['config']['table']['customize']"
            :scroll="{ x: columns.length * 150 }"
            :pagination="false"
            :dataSource="tableData"
            :columns="columns"
            :rowSelection="
              FormJson['config']['table']['extend']['batch']
                ? {
                    selectedRowKeys: selectedRowKeys,
                    onChange: onSelectChange
                  }
                : null
            "
          >
            <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
              <span :key="index">
                {{ col.customTitle }}
              </span>
            </template>
            <!-- eslint-disable-next-line prettier/prettier -->
            <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
              <div v-if="col.dataIndex === 'name'" :key="index">
                <span>{{ text }}</span>
              </div>
              <div v-else-if="col.dataIndex === 'money'" :key="index">
                <!-- <div>
                  <a-input-number :min="1" :disabled="!record.editable" v-model="record.money" style="width:120px" :precision="2" />
                </div> -->
                <span>{{ text }}</span>
              </div>
              <div v-else-if="col.dataIndex === 'identityBinding'" :key="index" style="position: relative">
                <a-popover title="数据错误" placement="right" :key="index">
                  <template slot="content">
                    <p>该员工微工卡未授权，请让员工前往小程序端进行绑定或者使用“微信扫码录入”进行微工卡绑定</p>
                  </template>
                  <div class="triangle" v-if="record.type === 2 && !record.identityBinding"></div>
                </a-popover>
                <span>{{ text ? "已绑定" : "未绑定" }}</span>
              </div>
              <div v-else-if="col.dataIndex === 'identity'" :key="index">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ text }}</span>
                  </template>
                  <div class="overflowsIdentity">{{ text }}</div>
                </a-tooltip>
              </div>
              <div v-else-if="col.dataIndex === 'bankName'" :key="index">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{{ text }}</span>
                  </template>
                  <div class="overflowsIdentity">{{ text }}</div>
                </a-tooltip>
              </div>
              <span v-else-if="col.dataIndex === 'tableAction'" :key="index">
                <!-- <span v-if="record.editable">
                  <a-popconfirm title="确定保存编辑?" @confirm="() => onSave(record.key)">
                    <a>确定</a>
                  </a-popconfirm>

                  <a-divider type="vertical" />
                  <a-popconfirm title="确定取消编辑?" @confirm="() => onCancel(record.key)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <span>
                    <a :disabled="editingKey !== ''" @click="onEdit(record.key)">编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      :title="`确认要删除吗？`"
                      ok-text="确认"
                      cancel-text="取消"
                      :disabled="editingKey !== ''"
                      @confirm="onClose(record.id)"
                    >
                      <a :disabled="editingKey !== ''">删除</a>
                    </a-popconfirm>
                  </span>
                </span> -->
                <a @click="onEditMoney(record.id)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm :title="`确认要删除吗？`" ok-text="确认" cancel-text="取消" @confirm="onClose(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
              <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" />
            </template>
          </XqTable>
          <div class="xq-form-content-pagination">
            <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
            <a-pagination
              v-model="pageNo"
              :total="total"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :page-size-options="['10', '20', '50', '100']"
              :page-size="pageSize"
              @change="onPageChange"
              @showSizeChange="onPageSizeChange"
            />
          </div>
        </a-spin>
      </div>
      <div class="sumbit">
        <a-button @click="$router.go(-1)" class="mr12"> 返回 </a-button>
        <a-button
          type="primary"
          :disabled="tableData.length <= 0 || (tableData[0].type == 2 && !tableData[0].identityBinding)"
          @click="handleSubmit"
        >
          发起申请
        </a-button>
      </div>

      <selectScope :visible.sync="selectScopeVisible" type="info" :companyId="info.companyId" @upDate="upDate" />
      <editMoney
        :visible.sync="editMoneyVisible"
        :selectedRowKeysId="selectedRowKeysId"
        :selectedRowKeys="selectedRowKeys"
        @upDate="upDateEditMoney"
      />
    </div>
    <abnormal v-else type="info" :arr="abnormalArr" @upDate="upDateAbnormal" />
  </div>
</template>

<script>
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import infoCard from "../component/infoCard";
import titborder from "../component/titborder";
import abnormal from "../abnormal";
import selectScope from "../add/selectPeople/selectScope";
import QrcodeForPay from "@/components/qrcodeForPay";
import editMoney from "../component/editMoney";
import {
  getTransferAccountsDetails,
  putTransferAccountsDetails,
  delTransferAccountsDetails,
  getStartApprover,
  getAllByCompany
} from "./api";
import moment from "moment";
import axios from "axios";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});
export default {
  mixins: [curdMixin],
  components: {
    infoCard,
    titborder,
    selectScope,
    abnormal,
    QrcodeForPay,
    editMoney
  },
  data() {
    return {
      spinning: false,
      tableData: [],
      tableData2: [],
      total: 0,
      pageNo: 1,
      pageSize: 20,
      editingKey: "",
      selectScopeVisible: false,
      selectedListTemp: [],
      dataJson: {},
      abnormalS: false,
      abnormalArr: "",
      fileList: [],
      infoid: "",
      info: {},
      editMoneyVisible: false,
      selectedRowKeys: [],
      selectedRowKeysId: []
    };
  },
  computed: {},
  created() {
    if (this.$route.query.id) {
      this.infoid = this.$route.query.id;
      sessionStorage.setItem("paySalaryInfoId", this.$route.query.id);
      sessionStorage.setItem("dataType", this.$route.query.dataType);
    } else {
      this.infoid = sessionStorage.getItem("paySalaryInfoId");
    }
    this.getColumns();
    this.onGetTransferAccountsDetails();
  },
  methods: {
    showQrcode() {
      if (this.$refs.infoCard) {
        const info = this.$refs.infoCard.getInfo();
        return info;
      }
      return false;
    },
    moment,
    async onGetTransferAccountsDetails() {
      try {
        this.visible = false;
        this.spinning = true;
        const { data } = await getTransferAccountsDetails({
          batchId: this.infoid,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          "orders[0].property": "identityBinding",
          "orders[0].desc": false
        });
        this.tableData = data.entities;
        this.tableData.map((e, i) => {
          e.key = i.toString();
          e.editable = false;
        });
        this.tableData2 = JSON.parse(JSON.stringify(this.tableData));
        this.total = data.entityCount;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        this.tableData = [];
        this.total = 0;
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    onPageChange(page) {
      this.selectedRowKeys = [];
      this.pageNo = page;
      this.onGetTransferAccountsDetails();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetTransferAccountsDetails();
    },
    async handleSubmit() {
      let lock = false;
      this.tableData.some((e) => {
        if (!e.money) {
          lock = true;
          return false;
        }
      });
      if (lock) {
        this.$notification["error"]({
          message: "人员未设置薪资"
        });
      } else {
        this.onGetAllByCompany();
      }
    },
    async onGetStartApprover(id) {
      try {
        await getStartApprover(this.infoid, id);
        this.$notification.success({ message: "操作成功" });
        this.$refs.infoCard.onGetTransferAccountsBatches();
        this.$router.replace({
          name: "applyForResults",
          query: {
            id: this.infoid
          }
        });
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    async onGetAllByCompany() {
      try {
        const { data } = await getAllByCompany("defaultTransferAccounts", {
          moduleType: "hr",
          type: "transferAccounts",
          inUse: true
        });
        if (data && data.length > 0) {
          this.onGetStartApprover(data[0].id);
        } else {
          this.$notification.error({ message: "未设置审批" });
        }
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onEdit(key) {
      const newData = [...this.tableData];
      const target = newData.filter((item) => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.tableData = newData;
      }
    },
    onSave(key) {
      const newData = [...this.tableData];
      const target = newData.filter((item) => key === item.key)[0];
      if (target) {
        this.onPutTransferAccountsDetails(target);
        target.editable = false;
        this.tableData = newData;
      }
      this.editingKey = "";
    },

    async onPutTransferAccountsDetails(v) {
      try {
        await putTransferAccountsDetails({
          id: v.id,
          money: v.money
        });
        this.$notification.success({ message: "操作成功" });
        this.onGetTransferAccountsDetails();
        this.$refs.infoCard.onGetTransferAccountsBatches();
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onCancel(key) {
      const newData = [...this.tableData];
      const newData2 = [...this.tableData2];
      const target = newData.filter((item) => key === item.key)[0];
      const target2 = newData2.filter((item) => key === item.key)[0];
      this.editingKey = "";
      if (target && target2) {
        Object.assign(target, target2);
        target.editable = false;
        this.tableData = newData;
      }
    },
    async onClose(id) {
      try {
        await delTransferAccountsDetails(id);
        this.$notification.success({ message: "操作成功" });
        this.onGetTransferAccountsDetails();
        this.$refs.infoCard.onGetTransferAccountsBatches();
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    upDate(arr) {
      if (arr && arr.length > 0) {
        this.abnormalS = true;
        this.abnormalArr = arr;
      } else {
        this.pageNo = 1;
        this.onGetTransferAccountsDetails();
      }
    },
    upDateAbnormal() {
      this.abnormalS = false;
      this.abnormalArr = [];
      this.pageNo = 1;
      this.onGetTransferAccountsDetails();
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message.error("最多只能上传一个");
        return false;
      }
      const info = JSON.parse(sessionStorage.getItem("paySalaryInfo"));
      const paySalaryCompanyId = info.companyId;
      const paySalaryTypes = info.type;
      this.fileList = [...this.fileList, file];
      if (this.fileList && this.fileList.length > 0) {
        const { fileList } = this;
        const formData = new FormData();
        fileList.forEach((file) => {
          formData.append("file", file);
          formData.append("companyId", paySalaryCompanyId);
          formData.append("batchId", this.infoid);
          formData.append("type", paySalaryTypes);
        });
        this.uploading = true;
        axios({
          url: ` /hr/api/v1/transferAccountsDetails/recognitionDetailInfo`,
          method: "post",
          data: formData,
          headers: this.headers
        })
          .then((res) => {
            this.handleSuccess(res.data);
            this.uploading = false;
          })
          .catch(() => {
            setTimeout(() => {
              this.reset();
            }, 1000);
            this.$notification["error"]({
              message: "error",
              description: "上传失败"
            });
          });
      } else {
        this.handleUploadError();
      }

      return false;
    },
    handleUploadError() {
      // this.$message.warning("没有文件");
    },
    handleSuccess(res) {
      var that = this;
      if (res.code === 200) {
        if (res.data) {
          this.$confirm({
            okText: "确定",
            title: `上传成功`,
            onOk() {
              if (res.data.failTransferAccountsDetailAddDTOList.length > 0) {
                that.abnormalS = true;
                that.abnormalArr = res.data.failTransferAccountsDetailAddDTOList;
                // sessionStorage.setItem("paySalaryInfoId", res.data.transferAccountsBatchVO.id);
              } else {
                that.onGetTransferAccountsDetails();
                that.$refs.infoCard.onGetTransferAccountsBatches();
              }
            }
          });
        } else {
          this.$notification["error"]({
            message: "error",
            description: "上传失败"
          });
        }
      } else if (res.data === null) {
        this.$confirm({
          okText: "确定",
          title: res.msg,
          cancelButtonProps: false
        });
      } else {
        this.$notification["error"]({
          message: "error",
          description: res.msg || "上传失败"
        });
      }
      setTimeout(() => {
        this.fileList = [];
      }, 1000);
    },
    onSelect() {
      this.selectScopeVisible = true;
      this.info = JSON.parse(sessionStorage.getItem("paySalaryInfo"));
    },
    onEditMoney(e) {
      this.selectedRowKeysId = [];
      if (e) {
        this.selectedRowKeysId = [e];
      }
      this.editMoneyVisible = true;
    },
    upDateEditMoney() {
      this.selectedRowKeys = [];
      this.onGetTransferAccountsDetails();
      this.$refs.infoCard.onGetTransferAccountsBatches();
    },
    getColumns() {
      const dataTypeDef = this.$route.query.dataType || sessionStorage.getItem("dataType");
      const dataType = parseInt(dataTypeDef);
      if (dataType) {
        if (dataType === 1) {
          const json = {
            customTitle: "支付宝号",
            dataIndex: "identity",
            model: "identity",
            scopedSlots: { customRender: "identity" },
            slots: { title: "xq_identity" }
          };
          this.columns.splice(-2, 0, json);
        }
        if (dataType === 2) {
          const json = {
            customTitle: "微工卡是否绑定",
            dataIndex: "identityBinding",
            model: "identityBinding",
            scopedSlots: { customRender: "identityBinding" },
            slots: { title: "xq_identityBinding" }
          };
          this.columns.splice(-2, 0, json);
        }
        if (dataType === 3) {
          const json = {
            customTitle: "银行卡号",
            dataIndex: "identity",
            model: "identity",
            scopedSlots: { customRender: "identity" },
            slots: { title: "xq_identity" }
          };
          const json1 = {
            customTitle: "银行名称",
            dataIndex: "bankName",
            model: "bankName",
            scopedSlots: { customRender: "bankName" },
            slots: { title: "xq_bankName" }
          };
          this.columns.splice(-2, 0, json, json1);
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.colw {
  width: 49%;
}
.tabs {
  height: 100px;
  background: rgba(255, 255, 255, 0);
  box-shadow: 0px 6px 16px 8px rgba(0, 0, 0, 0.03), 0px 4px 8px 0px rgba(0, 0, 0, 0.04);
  border-radius: 8px;
  border: 1px solid #fff;
  overflow: hidden;
  margin-top: 24px;
  text-align: center;
  color: #3c3d43;
  display: flex;
  justify-content: space-between;
  & > div {
    width: 25%;
    height: 98px;
    padding: 26px 0;
  }
  .tabs-item-one {
    line-height: 48px;
    border-right: 1px solid #e8e8e8;
    font-size: 16px;
    font-weight: 500;
  }
  .tabs-item {
    border-right: 1px solid #e8e8e8;
    font-size: 18px;
    font-weight: bold;
    cursor: pointer;
    &:hover {
      background: #f4f6fa;
    }
    &:nth-child(4) {
      border-right: 0;
    }
    & > div:nth-child(1) {
      font-size: 14px;
      font-weight: 400;
      color: #a6a8b4;
      margin-bottom: 4px;
    }
  }
}
.af-primary {
  color: var(--primary) !important;
}
.af-primary-border {
  border-color: var(--primary) !important;
}
.sumbit {
  position: fixed;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 56px;
  line-height: 56px;
  background: #fff;
  padding-left: 188px;
  text-align: center;
  box-shadow: 0px 2px 7px 0px rgba(0, 0, 0, 0.15);
  z-index: 1;
}
.triangle {
  position: absolute;
  top: -16px;
  left: -16px;
  width: 0;
  height: 0;
  // border-top: 20px solid transparent;
  border-left: 10px solid red;
  // border-right: 20px solid transparent;
  border-bottom: 10px solid transparent;
}
.overflowsIdentity {
  vertical-align: bottom;
  display: inline-block;
  max-width: 230px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
